package com.yzp.gateway;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * @title: MicroGateway
 * @Author: yzp
 * @Date: 2019/10/6 20:40
 * @Version 1.0
 */
//@Component
public class MicroGateway extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        //获取请求上下文，当请求进入Zuul，Zuul会给每个请求创建一个上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = ctx.getRequest();
        //获取请求参数中的token
        String token = request.getHeader("token");
        //判断是否为空
        if(token==null||"".equals(token)) {
            //为空拦截
            ctx.setSendZuulResponse(false);
            //设置状态码，没有权限
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("token is null");
            return null;
        }
        //不为空，放行
        return null;
    }
}
